package modulesAPI.v2.basics;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.caterina.components.CLabel;
import com.caterina.components.CPanel;
import com.caterina.components.CPasswordField;
import com.caterina.components.CTextField;
import com.caterina.resources.CModules;

import modulesAPI.v2.Module;
import modulesAPI.v2.ViewType;

public class ModTextField extends Module<String> implements DocumentListener{
	/**
	 * Crea un nuovo modulo per l'inserimento/rappresentazione di stringhe
	 * */
	public ModTextField(Module<?> ownerModule, String content, String tag,String description, ViewType viewType,int...options) {
		super(ownerModule, content, tag, description, viewType,options);
		if (isOptionEnabled(PASSWORD)){
			this.pwdField=new CPasswordField(this.getContent(),20);
			this.pwdField.getDocument().addDocumentListener(this);
		}else{
			this.textField=new CTextField(this.getContent(), 20, this.getDescription());
			this.textField.getDocument().addDocumentListener(this);
		}
	}
	@Override
	protected CPanel getReadOnlyPanel(boolean isSelected) {
		if(isOptionEnabled(PASSWORD))
			return CModules.formatPanelForReadOnlyPairs(this.getTag(),"••••••••");
		return CModules.formatPanelForReadOnlyPairs(this.getTag(), this.getContent());
	}
	@Override
	protected CPanel getWritablePanel(boolean isSelected) {
		if(isOptionEnabled(PASSWORD))	
			return CModules.formatForPairs(this.getTag(), pwdField);
		else
			return CModules.formatForPairs(this.getTag(), textField);
	}
	@Override
	public CPanel getInListPanel(boolean isSelected) {
			CPanel retPanel=new CPanel();
			if(isOptionEnabled(PASSWORD))
				retPanel.add(new CLabel("••••••••"));
			else	
				retPanel.add(new CLabel(this.getContent()));
			return retPanel;
	}
	@Override
	public void changedUpdate(DocumentEvent e) {}
	public int getHierachyNumber(){return -1;}
	@Override
	public void insertUpdate(DocumentEvent e) {		
		if (isOptionEnabled(PASSWORD))this.setContent(this.pwdField.getPwd());
		else this.setContent(textField.getText());
		this.fireModuleChanged(this);
	}
	@Override
	public void removeUpdate(DocumentEvent e) {
		if (isOptionEnabled(PASSWORD)) this.setContent(this.pwdField.getPwd());
		else this.setContent(textField.getText());
		this.fireModuleChanged(this);
	}
	@Override
	protected void beforeFireChange(Module<?> mod) {}
	@Override
	protected void afterFireChange(Module<?> mod) {}
	@Override
	protected CPanel getOneLinePanel(boolean isSelected) {
			return this.getReadOnlyPanel(isSelected);
	}
	private CPasswordField pwdField;
	private CTextField textField;
	public static final int PASSWORD=1;
}
